import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface ServerPorts {
  masterPort: number
  childPort: number
  websocketPort: number
}

export const useServerStore = defineStore('server', () => {
  // 服务器端口配置
  const ports = ref<ServerPorts>({
    masterPort: 3000,
    childPort: 3001,
    websocketPort: 3002
  })

  // 服务器状态
  const isServerRunning = ref(false)
  const serverStartTime = ref<Date | null>(null)

  // 更新端口配置
  const updatePorts = (newPorts: ServerPorts) => {
    ports.value = { ...newPorts }
    console.log('端口配置已更新:', ports.value)
  }

  // 设置服务器运行状态
  const setServerStatus = (running: boolean) => {
    isServerRunning.value = running
    if (running) {
      serverStartTime.value = new Date()
    } else {
      serverStartTime.value = null
    }
  }

  // 获取当前API基础URL
  const getApiBaseUrl = (type: 'main' | 'admin' | 'websocket') => {
    const baseUrl = '127.0.0.1'
    switch (type) {
      case 'main':
        return `http://${baseUrl}:${ports.value.masterPort}`
      case 'admin':
        return `http://${baseUrl}:${ports.value.childPort}`
      case 'websocket':
        return `${baseUrl}:${ports.value.websocketPort}`
      default:
        return `http://${baseUrl}:${ports.value.masterPort}`
    }
  }

  return {
    ports,
    isServerRunning,
    serverStartTime,
    updatePorts,
    setServerStatus,
    getApiBaseUrl
  }
})